﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace eslib.nnp5.Tools
{

    /// <summary>
    /// 周期性工作线程
    /// </summary>
    public class Worker
    {
        public int Cycle { get; }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="cycle">周期(毫秒),默认10秒</param>
        public Worker(int cycle = 10000)
        {
            this.Cycle = cycle;
        }


        /// <summary>
        /// 开始运行（周期性）
        /// </summary>
        /// <param name="action">工作</param>
        public async Task RunCycle(Action action)
        {
            cancel = new CancellationTokenSource();

            await Task.Run(async () =>
            {
                while (!cancel.IsCancellationRequested)
                {
                    action();       //工作

                    //等待下一轮
                    await Task.Delay(Cycle, cancel.Token);  //可通过cancel取消
                }
            }).ContinueWith(t =>
            {
                afterAction?.Invoke();
            });
        }



        /// <summary>
        /// 取消工作
        /// </summary>
        /// <param name="after">工作结束后运行,可选</param>
        public void Cancel(Action after = null)
        {
            afterAction = after;
            cancel.Cancel();
        }

        Action afterAction = null;
        CancellationTokenSource cancel;

    }
}
